import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class CreateExcel {
    public static String getExcel(List<String> title,List<String[]> data ,String filepath ){
        String realPath = filepath +"importExcel" + ".xls";
        try {
            File file = new File(realPath);//表格的输出路径
            FileOutputStream stream = new FileOutputStream(file);
            if (!file.exists()){
                file.mkdirs();
            }
            Workbook workbook = new HSSFWorkbook();//创建表格
            Sheet sheet = workbook.createSheet();//创建工作簿
            Row rowtitle = sheet.createRow(0);//创建行，里面是行的索引（0开头）
            for (int cellOrder=0;cellOrder<title.size();cellOrder++){
                Cell cell = rowtitle.createCell(cellOrder);
                cell.setCellValue(title.get(cellOrder));
            }
            for (int rowNum = 1; rowNum < data.size(); rowNum++) {
                Row rowContent = sheet.createRow(rowNum);
                for (int cellOrder = 0; cellOrder<data.get(rowNum-1).length;cellOrder++){
                    Cell cell = rowContent.createCell(cellOrder);
                    cell.setCellValue(data.get(rowNum-1)[cellOrder]);
                }
            }
            workbook.write(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return realPath;
    }

    public static void main(String[] args) {
        List<String> title = new ArrayList<String>();
        title.add("姓名");
        title.add("性别");
        title.add("爱好");
        List<String[]> content = new ArrayList<String[]>();
        content.add(new String[]{"小明","男","足球"});
        content.add(new String[]{"小红","女","音乐"});
        content.add(new String[]{"小李","男","篮球"});
        getExcel(title,content,"D:\\");
    }
}
